<?php
/**
 * Created by PhpStorm.
 * User: jacob
 * Date: 18-9-3
 * Time: 上午9:46
 * 登录接口
 */
namespace API;

use DB\AccountOrg;
use DB\Token;
use Tiny\HttpStatus;
use Tiny\JsonAPI;
use Tiny\Request;
use Tiny\Response;
use Tiny\ServiceRequestData;
use Tiny\ServiceResponseData;

class ServiceLoginRequestData extends ServiceRequestData{
  /**
   * 测试账号：测试账号　123456
   */
  public $account;
  public $password;

}
class ServiceLoginResponseData extends ServiceResponseData{
  public $uid;
  public $token;

}
class ServiceLogin extends JsonAPI {
  protected function run(Request $request, Response $response) {
    /**
     * @var $rqData ServiceLoginRequestData
     */
    $rqData = $request->data;
    if (!isset($rqData->account) || !is_string($rqData->account)){
      $response->httpStatus = HttpStatus::ARGS_ERROR;
      $response->httpStatusMsg = "account is not set or is not string";
      return;
    }
    if (!isset($rqData->password) || !is_string($rqData->password)){
      $response->httpStatus = HttpStatus::ARGS_ERROR;
      $response->httpStatusMsg = "password is not set or is not string";
      return;
    }
    $AccountOrg = new AccountOrg();
    if(!$AccountOrg->buildByAccount($rqData->account)){
      $response->httpStatus = HttpStatus::NOT_FOUND;
      $response->httpStatusMsg = "ACCOUNT IS NOT FOUND";
      return;
    }
    if (!$AccountOrg->verity($rqData->password)){
      $response->httpStatus = HttpStatus::NOT_ACCEPTABLE;
      $response->httpStatusMsg = "PASSWORD IS ERROR";
      return;
    }
    $token = new Token();
    $token->initWithUid($AccountOrg->getUid());
    $response->data = new ServiceLoginResponseData();
    $response->data->uid = $token->getUid();
    $response->data->token = $token->getToken();
  }
}